package ru.jexp.rcp.supply.beans.project.dvs;

import org.eclipse.jface.action.MenuManager;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CTabItem;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IEditorSite;

import ru.jexp.rcp.supply.beans.ek.JExpTreeViewerNEk;
import ru.jexp.rcp.supply.n.JExpTreeViewerN;
import ru.jexp.rcp.supply.swtext.JExpCTabFolder;
import ru.jexp.rcp.supply.swtext.JExpMouseAdapter;

public class DvsHolderCTabFolder extends JExpCTabFolder implements ListDvsHolderPresenter.IView
{

	public static final String ID_TAB_CONTEXT_MENU = "ru.jexp.rcp.supply.beans.project.dvs.tabcontextmenu";
	private static final String ID_VIEWER_CONTEXT_MENU = "ru.jexp.rcp.supply.beans.project.dvs.viewercontextmenu";

	private IEditorSite site;

	public DvsHolderCTabFolder(IEditorSite site, Composite parent)
	{
		super(parent, SWT.MULTI | SWT.FLAT | SWT.BOTTOM);
		this.site = site;
		getFolder().addMouseListener(new JExpMouseAdapter()
		{
			@Override
			public void mouseUpRight(MouseEvent e)
			{
				CTabItem item = getFolder().getItem(new Point(e.x, e.y));
				if (item != null)
				{
					getFolder().setSelection(item);
				}
			}
		});
		getFolder().addSelectionListener(new SelectionAdapter()
		{
			@Override
			public void widgetSelected(SelectionEvent e)
			{
				if (getFolder().getSelectionIndex() != -1)
				{
					DvsHolderCTabFolder.this.site.setSelectionProvider(getViewer(getFolder().getSelectionIndex()));
				}
				else
				{
					DvsHolderCTabFolder.this.site.setSelectionProvider(null);
				}
			}
		});
	}

	@Override
	public JExpTreeViewerNEk getViewer(int index)
	{
		if (index < getFolder().getItemCount())
		{
			return (JExpTreeViewerNEk) getItem(index).getData("viewer");
		}
		return null;
	}

	@Override
	public CTabItem createItem(int index)
	{
		Composite tabComposite = new Composite(getFolder(), SWT.NONE);
		tabComposite.setLayout(new FillLayout());

		CTabItem item = new CTabItem(getFolder(), SWT.NONE, index);
		item.setControl(tabComposite);

		item.setData("viewer", createEkView(tabComposite));

		return item;
	}

	public void refresh()
	{
		for (int i = 0; i < getItemCount(); i++)
		{
			getViewer(i).refresh();
		}
	}

	private JExpTreeViewerN createEkView(Composite parent)
	{
		JExpTreeViewerN viewer = new JExpTreeViewerNEk(parent);
		MenuManager mng = new MenuManager();
		viewer.getTree().setMenu(mng.createContextMenu(viewer.getTree()));
		site.registerContextMenu(ID_VIEWER_CONTEXT_MENU, mng, viewer);
		return viewer;

	}
}
